package weworkgo

import (
	"encoding/xml"
	"errors"
	"gitee.com/microrain/weworkgo/lib/wxbizmsgcrypt"
	"io/ioutil"

	"log"
	"net/http"
)

func (p *Provider) ParseWechatCorpTpInfoData(request *http.Request) (*WechatCorpTpInfoData, error) {

	body, err := ioutil.ReadAll(request.Body)

	if nil != err {
		log.Printf("Request read Body error: %s", err.Error())
		return nil, err
	}

	err = request.ParseForm()
	if nil != err {
		log.Printf("Request ParseForm error:(%s) %s", err.Error())
		return nil, err
	}
	receiverId := p.Config.SuiteId

	params := request.Form
	msgSign := params.Get("msg_signature")
	timeStamp := params.Get("timestamp")
	nonce := params.Get("nonce")
	echostr := params.Get("echostr")

	if echostr != "" {
		receiverId = params.Get("corpid")
	}
	wxCpt := wxbizmsgcrypt.NewWXBizMsgCrypt(p.Config.CallbackToken, p.Config.CallbackEncodingAESKey, receiverId, 1)

	if echostr != "" { // 验证推送URL
		msg, cErr := wxCpt.VerifyURL(msgSign, timeStamp, nonce, echostr)
		if cErr != nil {
			log.Printf("ParseWechatCorpTpInfoData DecryptMsg EchoStr error:SuiteId(%s) %s", receiverId, cErr.ErrMsg)
			return nil, errors.New(cErr.ErrMsg)
		}
		log.Printf("ParseWechatCorpTpInfoData:CorpId(%s) %s", p.Config.CorpId, msg)
		echoData := new(WechatCorpTpInfoData)
		echoData.InfoType = "echostr"
		echoData.EchoStr = string(msg)
		return echoData, nil
	}
	decryptMsg, cErr := wxCpt.DecryptMsg(msgSign, timeStamp, nonce, body)
	if cErr != nil {
		log.Printf("ParseWechatCorpTpInfoData DecryptMsg EchoStr error:CorpId(%s) %s", receiverId, cErr.ErrMsg)
		return nil, errors.New(cErr.ErrMsg)
	}
	//decryptMsg, err := cryptor.DecryptMsg(msgSign, timeStamp, nonce, body)
	if nil != err {
		log.Printf("ParseWechatCorpTpInfoData DecryptMsg error:CorpId(%s) %s", p.Config.CorpId, err.Error())
		return nil, err
	}

	log.Printf("ParseWechatCorpTpInfoData:CorpId(%s) %s", p.Config.CorpId, decryptMsg)
	infoData := new(WechatCorpTpInfoData)
	err = xml.Unmarshal([]byte(decryptMsg), infoData)
	if nil != err {
		log.Printf("ParseWechatCorpTpInfoData Unmarshal DecryptMsg error:CorpId(%s) %s", p.Config.CorpId, err.Error())
		return nil, err
	}

	return infoData, nil
}
